package cn.yjr.vector;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.yjr.vector.tools.MD5;
import cn.yjr.vector.tools.SharedPreferencesHelper;
import cn.yjr.vector.tools.YJRHttpClient;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;

public class UpdateHospitalActivity extends SherlockActivity{

	LayoutInflater inflater;
	ActionBar actionBar;
	View title_bar;
	Context context;
	String response;
	JSONObject jsonInfo;
	ListView hospital_lv;
	String info;
	SharedPreferencesHelper spHelper;
	JSONArray hospital_array;
	String name = null;
    String hospital_id = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_update_hospital);
		inflater = this.getLayoutInflater();
		actionBar = getSupportActionBar();
		context = this;
		this.spHelper = new SharedPreferencesHelper(this.context);
		
		getHospitalData();
		
		initTitleBar();
		
		
		
		
		
	
	}
	
	private void initTitleBar(){
		ActionBar.LayoutParams lp = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,ActionBar.LayoutParams.WRAP_CONTENT,Gravity.CENTER);
		title_bar = inflater.inflate(R.layout.update_hospital_action_bar, null);
		
		actionBar.setCustomView(title_bar,lp);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);
	}
	private void initComponent(){
		hospital_lv = (ListView) findViewById(R.id.hospital_list);
		hospital_lv.setAdapter(new MyAdapter(context));
	}
	
	private void initEventListener(){
		hospital_lv.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				JSONObject data = null;
	        	String key;
	        	try {
					name = hospital_array.getJSONObject(position).getString("text");
					hospital_id = hospital_array.getJSONObject(position).getString("id");
					update(hospital_id);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		});
		
	}	
	private void update(String hospital_id){
		RequestParams params = new RequestParams(); 
		params.add("hospitalId", hospital_id);
		final String hospitalid = hospital_id;
		YJRHttpClient.post(context,"/doctor/updateInfo", params, new JsonHttpResponseHandler(){
			 @Override  
	            public void onSuccess(JSONObject data) {  
	             	jsonInfo = data;
	             	try {
						if(jsonInfo.getInt("result") == 1){
							YJRHttpClient.setCookie(context); 
							Toast.makeText(context, "更新医院成功", Toast.LENGTH_LONG).show();
							Intent intent = new Intent();
							intent.putExtra("hospital_id", hospitalid);
							intent.putExtra("hospital_name", name);
							((Activity) context).setResult(Activity.RESULT_OK,intent);
							((Activity) context).finish();
						}else{
							Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }  
		});
	}
	
	private class MyAdapter extends BaseAdapter{  
	        private Context mContext;  
	        public MyAdapter(Context context) {  
	            this.mContext=context;  
	        }  
	        public int getCount() {  
	            return hospital_array.length(); 
	        }  
	  
	        public Object getItem(int position) { 
	        	JSONObject data = null;
	        	try {
					data = hospital_array.getJSONObject(position);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        	
	            return data;
	        }  
	  
	        public long getItemId(int position) {  
	            return position;  
	        }  
	        //用以生成在ListView中展示的一个个元素View  
	        public View getView(int position, View convertView, ViewGroup parent) {  
	            //优化ListView  
	            if(convertView==null){  
	                convertView=LayoutInflater.from(mContext).inflate(R.layout.degree_item, null);  
	                ItemViewCache viewCache=new ItemViewCache();  
	                viewCache.degree_tv=(TextView)convertView.findViewById(R.id.degree_name);   
	                convertView.setTag(viewCache);  
	            } 
	            ItemViewCache cache=(ItemViewCache)convertView.getTag();
				try {
					name = hospital_array.getJSONObject(position).getString("name");
					hospital_id = hospital_array.getJSONObject(position).getString("id");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	            cache.degree_tv.setText(name);
	            return convertView;  
	        }
	    }  
	    //元素的缓冲类,用于优化ListView  
	private static class ItemViewCache{  
	        public TextView degree_tv;  
	    }  
	

	private void getHospitalData(){
		RequestParams params = new RequestParams(); 
		params.add("areaId", "100");
		YJRHttpClient.post(context,"/data/listHospitalsOfArea.action", params, new JsonHttpResponseHandler(){
			 @Override  
	            public void onSuccess(JSONObject data) {  
	             	jsonInfo = data;
	             	try {
	             		if(jsonInfo.getInt("result") == 1){
							YJRHttpClient.setCookie(context); 
							hospital_array = data.getJSONArray("response");
							initComponent();
							
							initEventListener();
						}else{
							Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }  
		});
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
	      switch (requestCode) {
	      case 1:
	    	  String title = data.getStringExtra("title");
	    	  String category = data.getStringExtra("category");
	    	  update(category, title);
	    	  break;
	      default:  
	          break;  

	      }  
	      super.onActivityResult(requestCode, resultCode, data);  
	  }  
	
	private void update(String category, String title){
		RequestParams params = new RequestParams(); 
		params.add("category", category);
		params.add("title", title);
		YJRHttpClient.post(context,"/doctor/updateInfo.action", params, new JsonHttpResponseHandler(){
			 @Override  
	            public void onSuccess(JSONObject data) {  
	             	jsonInfo = data;
	             	try {

							YJRHttpClient.setCookie(context);
							if(jsonInfo.getInt("result") == 1){
								YJRHttpClient.setCookie(context); 
								Toast.makeText(context, "更改职称成功", Toast.LENGTH_LONG).show();
								UpdateHospitalActivity.this.finish();
							}else{
								Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
							}
							
							initEventListener();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }  
		});
	}
}